/*
 * Copyright 2000-2007 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jetbrains.idea.accurev.actions;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataKeys;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vcs.FileStatusManager;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.EnvironmentUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.idea.accurev.AccuRevBundle;
import org.jetbrains.idea.accurev.application.PerforceClient;
import org.jetbrains.idea.accurev.application.AccuRevManager;
import org.jetbrains.idea.accurev.accurev.FStat;
import org.jetbrains.idea.accurev.accurev.P4File;
import org.jetbrains.idea.accurev.accurev.AccuRevSettings;
import org.jetbrains.idea.accurev.accurev.connections.P4Connection;
import org.jetbrains.idea.accurev.accurev.connections.AccuRevConnectionManager;

import java.io.IOException;

/**
 * @author yole
 */
public class RevisionGraphAction extends AnAction {
  private static final Logger LOG = Logger.getInstance("#org.jetbrains.idea.accurev.actions.RevisionGraphAction");

  public void actionPerformed(AnActionEvent e) {
    final Project project = e.getData(DataKeys.PROJECT);
    final VirtualFile virtualFile = e.getData(DataKeys.VIRTUAL_FILE);
    assert project != null && virtualFile != null;
    final P4Connection connection = AccuRevConnectionManager.getInstance(project).getConnectionForFile(virtualFile);
    final PerforceClient client = AccuRevManager.getInstance(project).getClient(connection);
    final AccuRevSettings settings = AccuRevSettings.getSettings(project);
    @NonNls StringBuilder cmd = new StringBuilder(settings.PATH_TO_P4V + " -p ");
    cmd.append(client.getServerPort());
    cmd.append(" -u ");
    cmd.append(client.getUserName());
    cmd.append(" -c ").append(client.getName());
    if (SystemInfo.isWindows) {
      cmd.append(" -win 0");
    }
    cmd.append(" -cmd \"");
    cmd.append(getCommandName()).append(" ");

    FStat fStat = null;
    if (settings.ENABLED) {
      final P4File p4File = P4File.create(virtualFile);
      try {
        fStat = p4File.getFstat(project, false);
      }
      catch (VcsException ex) {
        Messages.showErrorDialog(project, AccuRevBundle.message("failed.to.retrieve.p4.status.information",
                                                                 FileUtil.toSystemDependentName(virtualFile.getPath()),
                                                                 ex.getMessage()),
                                 "AccuRev");
        return;
      }
    }
    if (fStat != null && !StringUtil.isEmpty(fStat.depotFile)) {
      cmd.append(fStat.depotFile);
    }
    else {
      cmd.append(FileUtil.toSystemDependentName(virtualFile.getPath()));
    }

    cmd.append("\"");

    try {
      Runtime.getRuntime().exec(cmd.toString(), EnvironmentUtil.getEnvironment());
    }
    catch (IOException ex) {
      Messages.showErrorDialog(project, AccuRevBundle.message("p4v.run.failed", ex.getMessage()), "P4V");
    }
  }

  @NonNls
  protected String getCommandName() {
    return "tree";
  }

  @Override
  public void update(final AnActionEvent e) {
    final Project project = e.getData(DataKeys.PROJECT);
    final VirtualFile virtualFile = e.getData(DataKeys.VIRTUAL_FILE);
    if (project == null || virtualFile == null || !virtualFile.isInLocalFileSystem()) {
      e.getPresentation().setEnabled(false);
    }
    else {
      FileStatus fileStatus = FileStatusManager.getInstance(project).getStatus(virtualFile);
      e.getPresentation().setEnabled(fileStatus != FileStatus.ADDED && fileStatus != FileStatus.UNKNOWN && fileStatus != FileStatus.IGNORED);
    }
  }
}